import type { Shape } from './shapes/Shape';
import { Rectangle } from './shapes/Rectangle';
import { Circle } from './shapes/Circle';
import { Cube } from './shapes/Cube';
import { Path } from './shapes/Path';
import type { StateManager } from './state-manager';
import { canvasStateProvider } from './state-provider';
import type { AnchorPoint } from './types';

export interface CanvasState {
  offsetX: number;
  offsetY: number;
  scale: number;
  lastX: number;
  lastY: number;
}

/**
 * 网格系统配置
 */
export interface GridSystemConfig {
  /** 基础网格大小（世界坐标） */
  baseGridSize: number;
  /** 网格级别切换阈值（屏幕像素） */
  gridSwitchThreshold: number;
  /** 主网格颜色 */
  primaryGridColor: string;
  /** 次级网格颜色 */
  secondaryGridColor: string;
  /** 三级网格颜色 */
  tertiaryGridColor: string;
  /** 坐标轴颜色 */
  axisColor: string;
  /** 缩放强度 */
  zoomIntensity: number;
  /** 最小缩放级别 */
  minScale: number;
  /** 最大缩放级别 */
  maxScale: number;
}

/**
 * 默认网格系统配置
 */
export const DEFAULT_GRID_CONFIG: GridSystemConfig = {
  baseGridSize: 100,
  gridSwitchThreshold: 20,
  primaryGridColor: '#aaaaaa',
  secondaryGridColor: '#cccccc50',
  tertiaryGridColor: '#e0e0e010',
  axisColor: '#ccc',
  zoomIntensity: 0.0005,
  minScale: 0.0001,
  maxScale: 10000
};

export interface CanvasManagerOptions {
  canvas: HTMLCanvasElement;
  stateManager: StateManager;
  gridConfig?: Partial<GridSystemConfig>;
  onCursorPositionChange?: (position: { x: number; y: number }) => void;
}

export class CanvasManager {
  private canvas: HTMLCanvasElement;
  private ctx: CanvasRenderingContext2D | null;
  private stateManager: StateManager;
  private gridConfig: GridSystemConfig;
  private onCursorPositionChange?: (position: { x: number; y: number }) => void;

  constructor(options: CanvasManagerOptions) {
    this.canvas = options.canvas;
    this.ctx = this.canvas.getContext('2d');
    this.stateManager = options.stateManager;
    this.gridConfig = { ...DEFAULT_GRID_CONFIG, ...options.gridConfig };
    this.onCursorPositionChange = options.onCursorPositionChange;

    this.initializeEventListeners();
    this.resizeCanvas();
  }

  // 初始化事件监听器
  private initializeEventListeners(): void {
    this.canvas.addEventListener('mousedown', this.handleMouseDown.bind(this));
    this.canvas.addEventListener('mousemove', this.handleMouseMove.bind(this));
    this.canvas.addEventListener('mouseup', this.handleMouseUp.bind(this));
    this.canvas.addEventListener(
      'mouseleave',
      this.handleMouseLeave.bind(this),
    );
    this.canvas.addEventListener('wheel', this.handleWheel.bind(this));

    window.addEventListener('resize', this.resizeCanvas.bind(this));
  }

  // 设置Canvas大小为窗口大小
  public resizeCanvas(): void {
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;

    const state = this.stateManager.getState();
    state.offsetX = this.canvas.width / 2;
    state.offsetY = this.canvas.height / 2;
    this.stateManager.updateState(state);

    this.draw();
  }

  // 绘制函数
  public draw(): void {
    if (!this.ctx) return;
    const state = this.stateManager.getState();

    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.ctx.save();

    // 应用坐标系变换
    this.ctx.translate(state.offsetX, state.offsetY);
    this.ctx.scale(state.scale, state.scale); // 保持Y轴不翻转

    this.drawCoordinateSystem();
    this.drawOrigin();
    this.drawShapes();

    // 绘制当前正在绘制的形状
    if (state.currentShape) {
      state.currentShape.draw(this.ctx);
    }

    this.ctx.restore();
    this.updatePositionInfo();
  }

  // 绘制坐标系
  private drawCoordinateSystem(): void {
    if (!this.ctx) return;

    // 绘制网格系统
    this.drawGridSystem();

    // 绘制坐标轴
    this.drawAxes();
  }

  /**
   * 绘制网格系统
   */
  private drawGridSystem(): void {
    if (!this.ctx) return;
    const state = this.stateManager.getState();
    const { gridSwitchThreshold, baseGridSize } = this.gridConfig;

    // 计算可视区域边界
    const left = -state.offsetX / state.scale;
    const top = state.offsetY / state.scale;
    const right = left + this.canvas.width / state.scale;
    const bottom = top - this.canvas.height / state.scale;

    this.ctx.lineWidth = 1 / state.scale;

    // 计算主网格大小（基于基础网格大小和缩放级别）
    const pixelGridSize = baseGridSize / state.scale;
    const log10 = Math.log10(pixelGridSize);
    const power = Math.floor(log10);
    let mainGridSize = Math.pow(10, power);

    // 动态调整网格级别：当网格在屏幕上小于阈值时升级
    if (mainGridSize * state.scale < gridSwitchThreshold) {
      mainGridSize = Math.pow(10, power + 1);
    }

    // 计算次级和三级网格大小
    const subGridSize = mainGridSize / 5;
    const tertiaryGridSize = mainGridSize / 25;

    // 确保网格线对齐整数
    const startX = Math.floor(left / mainGridSize) * mainGridSize;
    const startY = Math.ceil(top / mainGridSize) * mainGridSize;

    // 绘制主网格线
    this.ctx.strokeStyle = this.gridConfig.primaryGridColor;
    this.ctx.lineWidth = 1 / state.scale;

    for (let x = startX; x < right; x += mainGridSize) {
      // 判断是否为第5根线（以坐标轴为中心）
      const isMainLine = Math.abs(x % (mainGridSize * 5)) < 0.001;
      this.ctx.strokeStyle = isMainLine ? this.gridConfig.primaryGridColor : this.gridConfig.secondaryGridColor;
      this.ctx.beginPath();
      this.ctx.moveTo(x, -top);
      this.ctx.lineTo(x, -bottom);
      this.ctx.stroke();
    }

    for (let y = startY; y > bottom; y -= mainGridSize) {
      // 判断是否为第5根线（以坐标轴为中心）
      const isMainLine = Math.abs(y % (mainGridSize * 5)) < 0.001;
      this.ctx.strokeStyle = isMainLine ? this.gridConfig.primaryGridColor : this.gridConfig.secondaryGridColor;
      this.ctx.beginPath();
      this.ctx.moveTo(left, -y);
      this.ctx.lineTo(right, -y);
      this.ctx.stroke();
    }

    // 绘制次级网格线（当次级网格在屏幕上足够大时显示）
    if (subGridSize * state.scale > this.gridConfig.gridSwitchThreshold) {
      this.ctx.strokeStyle = this.gridConfig.secondaryGridColor;
      this.ctx.lineWidth = 1 / state.scale;

      for (let x = startX; x < right; x += subGridSize) {
        // 跳过主网格线位置
        if (Math.abs(x % mainGridSize) < 0.001) continue;
        this.ctx.beginPath();
        this.ctx.moveTo(x, -top);
        this.ctx.lineTo(x, -bottom);
        this.ctx.stroke();
      }

      for (let y = startY; y > bottom; y -= subGridSize) {
        // 跳过主网格线位置
        if (Math.abs(y % mainGridSize) < 0.001) continue;
        this.ctx.beginPath();
        this.ctx.moveTo(left, -y);
        this.ctx.lineTo(right, -y);
        this.ctx.stroke();
      }
    }

    // 绘制三级网格线（当三级网格在屏幕上足够大时显示）
    if (tertiaryGridSize * state.scale > this.gridConfig.gridSwitchThreshold) {
      this.ctx.strokeStyle = this.gridConfig.tertiaryGridColor;
      this.ctx.lineWidth = 1 / state.scale;

      for (let x = startX; x < right; x += tertiaryGridSize) {
        // 跳过主网格和次级网格线位置
        if (Math.abs(x % mainGridSize) < 0.001 || Math.abs(x % subGridSize) < 0.001) continue;
        this.ctx.beginPath();
        this.ctx.moveTo(x, -top);
        this.ctx.lineTo(x, -bottom);
        this.ctx.stroke();
      }

      for (let y = startY; y > bottom; y -= tertiaryGridSize) {
        // 跳过主网格和次级网格线位置
        if (Math.abs(y % mainGridSize) < 0.001 || Math.abs(y % subGridSize) < 0.001) continue;
        this.ctx.beginPath();
        this.ctx.moveTo(left, -y);
        this.ctx.lineTo(right, -y);
        this.ctx.stroke();
      }
    }
  }

  /**
   * 绘制坐标轴
   */
  private drawAxes(): void {
    if (!this.ctx) return;
    const state = this.stateManager.getState();

    // 计算可视区域边界
    const left = -state.offsetX / state.scale;
    const top = state.offsetY / state.scale;
    const right = left + this.canvas.width / state.scale;
    const bottom = top - this.canvas.height / state.scale;

    // 绘制坐标轴
    this.ctx.strokeStyle = this.gridConfig.axisColor;
    this.ctx.lineWidth = 1.5 / state.scale;
    this.ctx.beginPath();
    this.ctx.moveTo(left, 0);
    this.ctx.lineTo(right, 0);
    this.ctx.stroke();
    this.ctx.beginPath();
    this.ctx.moveTo(0, -top);
    this.ctx.lineTo(0, -bottom);
    this.ctx.stroke();
  }

  // 绘制原点标记
  private drawOrigin(): void {
    if (!this.ctx) return;
    const state = this.stateManager.getState();

    this.ctx.fillStyle = 'red';
    this.ctx.beginPath();
    this.ctx.arc(0, 0, 5 / state.scale, 0, Math.PI * 2);
    this.ctx.fill();

    this.ctx.font = `${12 / state.scale}px Arial`;
    this.ctx.fillStyle = 'red';
    this.ctx.fillText('(0,0)', 10 / state.scale, -10 / state.scale);
  }

  // 绘制所有形状
  private drawShapes(): void {
    if (!this.ctx) return;
    const shapes = this.stateManager.getShapes();

    shapes.forEach((shape) => {
      if (this.ctx) {
        shape.draw(this.ctx);

        // 绘制选中状态
        if (shape.selected) {
          shape.drawSelection(this.ctx);
        }
      }
    });
  }

  // 更新位置信息显示
  private updatePositionInfo(): void {
    const state = this.stateManager.getState();
    const worldPos = this.screenToWorld(state.lastX, state.lastY);

    // 更新UI显示位置信息
    if (this.onCursorPositionChange) {
      this.onCursorPositionChange(worldPos);
    }
  }

  // 世界坐标转屏幕坐标
  public worldToScreen(x: number, y: number): { x: number; y: number } {
    const state = this.stateManager.getState();
    return {
      x: x * state.scale + state.offsetX,
      y: -y * state.scale + state.offsetY, // Y轴翻转
    };
  }

  // 屏幕坐标转世界坐标
  public screenToWorld(x: number, y: number): { x: number; y: number } {
    const state = this.stateManager.getState();
    return {
      x: (x - state.offsetX) / state.scale,
      y: -(y - state.offsetY) / state.scale, // Y轴翻转
    };
  }

  // 鼠标事件处理
  private handleMouseDown(e: MouseEvent): void {
    const state = this.stateManager.getState();
    const worldPos = this.screenToWorld(e.clientX, e.clientY);
    const worldX = worldPos.x;
    const worldY = worldPos.y;

    state.lastX = e.clientX;
    state.lastY = e.clientY;
    this.stateManager.updateState(state);

    const mode = this.stateManager.getMode();

    switch (mode) {
      case 'select':
        this.handleSelectModeMouseDown(e, worldX, worldY);
        break;
      case 'draw':
      case 'rectangle':
      case 'circle':
      case 'path':
      case 'cube':
        this.handleDrawModeMouseDown(worldX, worldY);
        break;
    }
  }

  private handleSelectModeMouseDown(
    _e: MouseEvent,
    worldX: number,
    worldY: number,
  ): void {
    const selectedShape = this.stateManager.getSelectedShape();

    // 首先检查是否点击了锚点
    if (selectedShape && this.isPointInAnchor(worldX, worldY, selectedShape)) {
      const clickedAnchor = this.getClickedAnchor(worldX, worldY, selectedShape);
      if (clickedAnchor) {
        this.stateManager.updateState({
          isResizingShape: true,
          resizingAnchor: clickedAnchor,
          dragStartX: worldX,
          dragStartY: worldY
        });
        this.canvas.style.cursor = 'crosshair';
        return;
      }
    }

    if (selectedShape?.contains(worldX, worldY)) {
      this.stateManager.setMovingShape(true);
      this.stateManager.updateState({
        dragStartX: worldX,
        dragStartY: worldY
      });
      this.canvas.style.cursor = 'move';
    } else if (this.isPointInAnyShape(worldX, worldY)) {
      this.selectShape(worldX, worldY);
      this.stateManager.updateState({ isSelecting: true });
    } else {
      this.stateManager.setDragging(true, worldX, worldY);
      this.canvas.style.cursor = 'grabbing';
    }
  }

  private handleDrawModeMouseDown(worldX: number, worldY: number): void {
    const color = this.stateManager.getState().strokeColor;
    const lineWidth = this.stateManager.getState().strokeWidth;
    const mode = this.stateManager.getMode();

    let newShape: Shape | null = null;

    switch (mode) {
      case 'draw':
        newShape = new Path(
          worldX,
          worldY,
          color,
          lineWidth,
          canvasStateProvider,
        );
        break;
      case 'rectangle':
        newShape = new Rectangle(
          worldX,
          worldY,
          color,
          lineWidth,
          canvasStateProvider,
        );
        break;
      case 'circle':
        newShape = new Circle(
          worldX,
          worldY,
          color,
          lineWidth,
          canvasStateProvider,
        );
        break;
      case 'cube':
        newShape = new Cube(
          worldX,
          worldY,
          color,
          lineWidth,
          canvasStateProvider,
        );
        break;
      case 'path':
        newShape = new Path(
          worldX,
          worldY,
          color,
          lineWidth,
          canvasStateProvider,
        );
        break;
    }

    if (newShape) {
      this.stateManager.setDrawing(true, newShape);
    }
  }

  private handleMouseMove(e: MouseEvent): void {
    const state = this.stateManager.getState();
    const currentX = e.clientX;
    const currentY = e.clientY;
    const worldPos = this.screenToWorld(currentX, currentY);
    const worldX = worldPos.x;
    const worldY = worldPos.y;

    if (state.isDrawing && state.currentShape) {
      // 对于Path形状，需要特殊处理 - 持续添加点而不是更新终点
      if (state.currentShape instanceof Path) {
        state.currentShape.addPoint(worldX, worldY);
      } else {
        state.currentShape.updateEnd(worldX, worldY);
      }
      this.draw();
    } else if (state.isMovingShape && state.selectedShape) {
      this.handleShapeMove(worldX, worldY);
    } else if (state.isResizingShape && state.selectedShape) {
      this.handleShapeResize(worldX, worldY);
    } else if (state.isDragging) {
      this.handleCanvasDrag(currentX, currentY);
    }

    this.stateManager.setLastPosition(currentX, currentY);
    this.updatePositionInfo();
  }

  private handleShapeMove(worldX: number, worldY: number): void {
    const selectedShape = this.stateManager.getSelectedShape();
    if (!selectedShape) return;

    const state = this.stateManager.getState();
    const dx = worldX - state.dragStartX;
    const dy = worldY - state.dragStartY;

    // 移动形状
    if (selectedShape instanceof Path) {
      selectedShape.points.forEach((point) => {
        point.x += dx;
        point.y += dy;
      });
    } else if (selectedShape instanceof Circle) {
      selectedShape.x += dx;
      selectedShape.y += dy;
    } else if (selectedShape instanceof Rectangle) {
      selectedShape.x += dx;
      selectedShape.y += dy;
      selectedShape.endX += dx;
      selectedShape.endY += dy;
    } else if (selectedShape instanceof Cube) {
      selectedShape.x += dx;
      selectedShape.y += dy;
      selectedShape.endX += dx;
      selectedShape.endY += dy;
    }

    this.stateManager.updateState({
      dragStartX: worldX,
      dragStartY: worldY
    });

    if (selectedShape.createAnchors) {
      selectedShape.createAnchors();
    }

    this.draw();
  }

  private handleCanvasDrag(currentX: number, currentY: number): void {
    const state = this.stateManager.getState();
    const dx = currentX - state.lastX;
    const dy = currentY - state.lastY;

    state.offsetX += dx;
    state.offsetY += dy;
    this.stateManager.updateState(state);

    this.draw();
  }

  private handleMouseUp(): void {
    const state = this.stateManager.getState();

    if (state.isDrawing && state.currentShape) {
      this.stateManager.addShape(state.currentShape);
      this.stateManager.setDrawing(false, null);
    } else if (state.isMovingShape) {
      this.stateManager.setMovingShape(false);
      this.canvas.style.cursor = 'default';
    } else if (state.isResizingShape) {
      this.stateManager.updateState({
        isResizingShape: false,
        resizingAnchor: null
      });
      this.canvas.style.cursor = 'default';
    } else if (state.isDragging) {
      this.stateManager.setDragging(false, 0, 0);
      this.canvas.style.cursor = 'default';
    } else if (state.isSelecting) {
      this.stateManager.updateState({ isSelecting: false });
    }
  }

  private handleMouseLeave(): void {
    const state = this.stateManager.getState();
    if (state.isDrawing && state.currentShape) {
      this.stateManager.addShape(state.currentShape);
      this.stateManager.updateState({ currentShape: null, isDrawing: false });
    } else if (state.isDragging) {
      this.stateManager.updateState({ isDragging: false });
      this.canvas.style.cursor = 'default';
    } else if (state.isSelecting) {
      this.stateManager.updateState({ isSelecting: false });
    }
  }

  private handleWheel(e: WheelEvent): void {
    e.preventDefault();

    const state = this.stateManager.getState();
    const mouseX = e.clientX;
    const mouseY = e.clientY;
    const worldPos = this.screenToWorld(mouseX, mouseY);
    const worldX = worldPos.x;
    const worldY = worldPos.y;

    // 使用更平滑的缩放因子，参考Windows Paint的缩放体验
    const delta = -e.deltaY;
    const zoomFactor = 1 + delta * this.gridConfig.zoomIntensity;

    const newScale = state.scale * zoomFactor;
    // 限制缩放范围
    state.scale = Math.max(this.gridConfig.minScale, Math.min(this.gridConfig.maxScale, newScale));

    // 保持鼠标位置在世界坐标系中不变
    state.offsetX = mouseX - worldX * state.scale;
    state.offsetY = mouseY - -worldY * state.scale;

    this.stateManager.updateState(state);
    this.draw();
  }

  // 检查点是否在任何形状内
  private isPointInAnyShape(x: number, y: number): boolean {
    const shapes = this.stateManager.getShapes();

    for (let i = shapes.length - 1; i >= 0; i--) {
      if (shapes[i].contains(x, y)) {
        return true;
      }
    }
    return false;
  }

  // 检查点是否在锚点内
  private isPointInAnchor(x: number, y: number, shape: Shape): boolean {
    const scale = this.stateManager.getState().scale;
    const hitDistance = 8 / scale; // 锚点点击范围

    return shape.anchors.some((anchor) => {
      const dx = x - anchor.x;
      const dy = y - anchor.y;
      return Math.sqrt(dx * dx + dy * dy) <= hitDistance;
    });
  }

  // 获取点击的锚点
  private getClickedAnchor(x: number, y: number, shape: Shape): AnchorPoint | null {
    const scale = this.stateManager.getState().scale;
    const hitDistance = 8 / scale;

    for (const anchor of shape.anchors) {
      const dx = x - anchor.x;
      const dy = y - anchor.y;
      if (Math.sqrt(dx * dx + dy * dy) <= hitDistance) {
        return anchor;
      }
    }
    return null;
  }

  // 选择形状
  private selectShape(x: number, y: number): void {
    const selectedShape = this.stateManager.getSelectedShape();

    if (selectedShape) {
      selectedShape.selected = false;
      this.stateManager.updateState({ selectedShape: null });
    }

    const shapes = this.stateManager.getShapes();

    for (let i = shapes.length - 1; i >= 0; i--) {
      const shape = shapes[i];
      if (shape.contains(x, y)) {
        shape.selected = true;
        // 创建锚点
        if (shape.createAnchors) {
          shape.createAnchors();
        }
        this.stateManager.updateState({ selectedShape: shape });
        break;
      }
    }

    this.draw();
  }

  // 处理形状调整大小
  private handleShapeResize(worldX: number, worldY: number): void {
    const selectedShape = this.stateManager.getSelectedShape();
    const state = this.stateManager.getState();
    if (!selectedShape || !state.resizingAnchor) return;

    this.stateManager.setLastPosition(worldX, worldY);

    // 根据锚点类型调整形状
    const anchorType = state.resizingAnchor.type;

    if (selectedShape instanceof Rectangle) {
      this.resizeRectangle(selectedShape, anchorType, worldX, worldY);
    } else if (selectedShape instanceof Circle) {
      this.resizeCircle(selectedShape, anchorType, worldX, worldY);
    } else if (selectedShape instanceof Path) {
      this.resizePath(selectedShape, anchorType, worldX, worldY);
    } else if (selectedShape instanceof Cube) {
      this.resizeCube(selectedShape, anchorType, worldX, worldY);
    }

    // 更新拖拽起始位置，用于下一帧的增量计算
    this.stateManager.updateState({
      dragStartX: worldX,
      dragStartY: worldY
    });

    // 重新创建锚点
    if (selectedShape.createAnchors) {
      selectedShape.createAnchors();
    }

    this.draw();
  }

  // 调整矩形大小
  private resizeRectangle(rect: Rectangle, anchorType: string, worldX: number, worldY: number): void {
    const state = this.stateManager.getState();
    const dx = worldX - state.dragStartX;
    const dy = worldY - state.dragStartY;
    
    switch (anchorType) {
      case 'nw':
        rect.x += dx;
        rect.y += dy;
        break;
      case 'ne':
        rect.endX += dx;
        rect.y += dy;
        break;
      case 'se':
        rect.endX += dx;
        rect.endY += dy;
        break;
      case 'sw':
        rect.x += dx;
        rect.endY += dy;
        break;
      case 'n':
        rect.y += dy;
        break;
      case 'e':
        rect.endX += dx;
        break;
      case 's':
        rect.endY += dy;
        break;
      case 'w':
        rect.x += dx;
        break;
    }
  }

  // 调整圆形大小
  private resizeCircle(circle: Circle, anchorType: string, worldX: number, worldY: number): void {
    switch (anchorType) {
      case 'n':
        circle.radius = Math.abs(circle.y - worldY);
        break;
      case 'e':
        circle.radius = Math.abs(worldX - circle.x);
        break;
      case 's':
        circle.radius = Math.abs(worldY - circle.y);
        break;
      case 'w':
        circle.radius = Math.abs(circle.x - worldX);
        break;
    }
    circle.radius = Math.max(0, circle.radius);
  }

  // 调整立方体大小
  private resizeCube(cube: Cube, anchorType: string, worldX: number, worldY: number): void {
    const state = this.stateManager.getState();
    const dx = worldX - state.dragStartX;
    const dy = worldY - state.dragStartY;
    
    switch (anchorType) {
      case 'nw':
        cube.x += dx;
        cube.y += dy;
        break;
      case 'ne':
        cube.endX += dx;
        cube.y += dy;
        break;
      case 'se':
        cube.endX += dx;
        cube.endY += dy;
        break;
      case 'sw':
        cube.x += dx;
        cube.endY += dy;
        break;
      case 'n':
        cube.y += dy;
        break;
      case 'e':
        cube.endX += dx;
        break;
      case 's':
        cube.endY += dy;
        break;
      case 'w':
        cube.x += dx;
        break;
    }
  }

  // 调整路径大小（等比缩放）
  private resizePath(path: Path, anchorType: string, worldX: number, worldY: number): void {
    const bounds = path.getBounds();
    if (!bounds) return;

    const centerX = (bounds.left + bounds.right) / 2;
    const centerY = (bounds.top + bounds.bottom) / 2;

    let scaleX = 1;
    let scaleY = 1;

    switch (anchorType) {
      case 'nw':
        scaleX = (centerX - worldX) / (centerX - bounds.left);
        scaleY = (centerY - worldY) / (centerY - bounds.top);
        break;
      case 'ne':
        scaleX = (worldX - centerX) / (bounds.right - centerX);
        scaleY = (centerY - worldY) / (centerY - bounds.top);
        break;
      case 'se':
        scaleX = (worldX - centerX) / (bounds.right - centerX);
        scaleY = (worldY - centerY) / (bounds.bottom - centerY);
        break;
      case 'sw':
        scaleX = (centerX - worldX) / (centerX - bounds.left);
        scaleY = (worldY - centerY) / (bounds.bottom - centerY);
        break;
    }

    // 保持等比缩放，避免除零错误
    const scale = Math.max(scaleX, scaleY, 0.1); // 最小缩放比例为0.1

    path.points.forEach((point) => {
      point.x = centerX + (point.x - centerX) * scale;
      point.y = centerY + (point.y - centerY) * scale;
    });
  }

  // 清理方法 - 移除所有事件监听器
  public cleanup(): void {
    this.canvas.removeEventListener('mousedown', this.handleMouseDown.bind(this));
    this.canvas.removeEventListener('mousemove', this.handleMouseMove.bind(this));
    this.canvas.removeEventListener('mouseup', this.handleMouseUp.bind(this));
    this.canvas.removeEventListener('mouseleave', this.handleMouseLeave.bind(this));
    this.canvas.removeEventListener('wheel', this.handleWheel.bind(this));

    window.removeEventListener('resize', this.resizeCanvas.bind(this));
  }

  // 清空画布
  public clearCanvas(): void {
    this.stateManager.updateState({ shapes: [] });
    this.stateManager.updateState({ selectedShape: null });
    this.draw();
  }

  // 重置视图到原点
  public resetView(): void {
    const state = this.stateManager.getState();
    state.offsetX = this.canvas.width / 2;
    state.offsetY = this.canvas.height / 2;
    state.scale = 1;
    this.stateManager.updateState(state);
    this.draw();
  }

  /**
   * 更新网格系统配置
   */
  public updateGridConfig(config: Partial<GridSystemConfig>): void {
    this.gridConfig = { ...this.gridConfig, ...config };
    this.draw();
  }

  /**
   * 获取当前网格系统配置
   */
  public getGridConfig(): GridSystemConfig {
    return { ...this.gridConfig };
  }

  /**
   * 获取当前网格信息（用于调试和显示）
   */
  public getGridInfo(): {
    mainGridSize: number;
    subGridSize: number;
    tertiaryGridSize: number;
    screenMainGridSize: number;
    screenSubGridSize: number;
    screenTertiaryGridSize: number;
  } {
    const state = this.stateManager.getState();
    const { baseGridSize, gridSwitchThreshold } = this.gridConfig;

    // 计算主网格大小
    const pixelGridSize = baseGridSize / state.scale;
    const log10 = Math.log10(pixelGridSize);
    const power = Math.floor(log10);
    let mainGridSize = Math.pow(10, power);

    if (mainGridSize * state.scale < gridSwitchThreshold) {
      mainGridSize = Math.pow(10, power + 1);
    }

    const subGridSize = mainGridSize / 5;
    const tertiaryGridSize = mainGridSize / 25;

    return {
      mainGridSize,
      subGridSize,
      tertiaryGridSize,
      screenMainGridSize: mainGridSize * state.scale,
      screenSubGridSize: subGridSize * state.scale,
      screenTertiaryGridSize: tertiaryGridSize * state.scale
    };
  }

  // 更新形状属性
  public updateShapeProperty(property: string, value: string): void {
    const selectedShape = this.stateManager.getSelectedShape();
    if (!selectedShape) return;

    selectedShape.updateProperty(property, value);

    // 如果形状有createAnchors方法，重新创建锚点
    if (selectedShape.createAnchors) {
      selectedShape.createAnchors();
    }

    // 通知状态管理器属性已更新，触发重新渲染
    this.stateManager.updateState({});

    this.draw();
  }
}
